package javaer.starter.idea.action;

import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.psi.PsiFile;
import javaer.starter.idea.util.IdeaFileUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.awt.*;
import java.io.IOException;

import static javaer.starter.JavaerStarter.FILE_DIRECTORY;
import static javaer.starter.JavaerStarter.JAVAER_STARTER_TEMPLATE;

/**
 * @author yangzhen
 * @date 2023/8/9 11:01
 * @since 1.0.0
 */
public class SettingsDialog extends DialogWrapper implements Disposable {

    public final Project project;

    public final AnActionEvent e;

    private JTextField textField;

    public SettingsDialog(@Nullable Project project, AnActionEvent e) {
        super(project, true);
        this.e = e;
        this.project = project;
        setTitle("模板配置");
        setResizable(true);
        init();
    }

    @Nullable
    @Override
    protected JComponent createCenterPanel() {
        JPanel panel = new JPanel(new GridLayout(2, 2));

        JLabel label = new JLabel("基础包名:");

        textField = new JTextField();

        panel.add(label);
        panel.add(textField);

        return panel;
    }

    @Override
    protected Action @NotNull [] createActions() {
        return new Action[]{getOKAction(), getCancelAction()};
    }

    @Override
    protected void doOKAction() {
        PsiFile thisFile = e.getRequiredData(CommonDataKeys.PSI_FILE);
        String text = thisFile.getText();
        try {
            IdeaFileUtils.openFileEditor(project, new String[]{JAVAER_STARTER_TEMPLATE, FILE_DIRECTORY}, thisFile.getName() + ".ftl", text);
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
        super.doOKAction();
    }

    @Override
    public void dispose() {
        super.dispose();
    }

}
